package com.xzp.bams.client;

import com.xzp.bams.entity.Account;
import com.xzp.bams.service.Bank;

import javax.swing.*;
import java.awt.*;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.PrintWriter;
import java.net.ConnectException;
import java.net.Socket;

/**
 * @TODO
 * @Author xu
 * 2025/3/22
 */
public class ATMClient extends JFrame{
    MainPanel mainPanel;
    LoginPanel loginPanel;
   RgisterPanel rgisterPanel;
    BusinessPanel businessPanel;

    //共同数据
    Bank bank;
    Account account;


    //网络编程的资源
    Socket socket;
    PrintWriter pw;
    ObjectInputStream ois;


ObjectOutputStream objectOutputStream;
    public ATMClient() {
        //设置窗体的基本信息
        this.setTitle("ATM 取款机");
        //设置关闭方式，关闭即退出
        this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        //设置窗体的尺寸
        this.setSize(500, 600);
        //居中显示
        this.setLocationRelativeTo(getOwner());

        //初始化共同数据
        bank = Bank.getInstance();

        try {
            socket = new Socket("192.168.152.1", 8080);
            pw= new PrintWriter(socket.getOutputStream());
            ois = new ObjectInputStream(socket.getInputStream());
        } catch (ConnectException e) {
            JOptionPane.showMessageDialog(this, "服务器连接失败，请稍后再试！", "提示", JOptionPane.WARNING_MESSAGE);
            System.exit(0);
        }catch( IOException e){
            throw new RuntimeException(e);
        }

        //点击x关闭按钮，关闭程序
        this.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                //发送指令 PrintWriter 关闭指令close
                pw.println("close");
                pw.flush();

                try {
                    //读 空数据
                    ois.readObject();
                    //关闭客户端资源
                    socket.close();
                } catch (IOException ex) {
                    JOptionPane.showMessageDialog(null , "客户端已关闭！");
                } catch (ClassNotFoundException ex) {
                    throw new RuntimeException(ex);
                }

                System.exit(0);
            }
        });


        //实例化JPanel界面
        mainPanel = new MainPanel(this);
        loginPanel = new LoginPanel(this);
        rgisterPanel = new RgisterPanel(this);
        businessPanel = new BusinessPanel(this);

        //将JPanel添加至JFrame窗体容器中
        Container container = this.getContentPane();
        //设置容器为卡片式布局
        container.setLayout(new CardLayout());
        //默认显示第一个
        container.add(mainPanel, "mainPanel");
        container.add(loginPanel, "loginPanel");
        container.add(rgisterPanel, "rgisterPanel");
        container.add(businessPanel, "businessPanel");
    }


    public static void main(String[] args) {
        new ATMClient().setVisible(true);
    }
}